package implementation1.app.commands;

import exceptions.CommandErrorFromUserException;
import exceptions.CommandException;
import implementation1.app.Global;
import interfaces.app.IProcess;
import interfaces.data.IHandle;

import java.io.File;

/**
 * Class for handle command "cd" for changing directory.
 * Created: 18.10.11
 *
 * @author Jan Svab
 */
public class Cd extends Command
{
    /**
     * Default constructor.
     *
     * @param parent parent process over which is command processed
     * @param handle parameters of command
     */
    public Cd(IProcess parent, IHandle handle)
    {
        super(parent, handle);
    }

    /**
     * Main method for processing of command.
     *
     * @param args arguments of command
     * @throws CommandException Thrown if occurs error during processing of the command.
     */
    @Override
    public void mainCommand(String[] args) throws CommandException
    {
        File newPathFile;

        if (args != null && args.length == 1)
        {
            newPathFile = Global.getFileWithAbsPath(handle.getActualPath(), args[0]);
        }
        else if (args == null || args.length == 0)
        {
            newPathFile = File.listRoots()[0];
        }
        else
        {
            throw new CommandErrorFromUserException(bundle.getString("error.arguments.wrongCount"));
        }

        if (newPathFile.exists() && newPathFile.isDirectory())
        {
            parentProcess.getHandle().setActualPath(Global.normalizePath(newPathFile).getAbsolutePath());
        }
        else
        {
            throw new CommandErrorFromUserException(bundle.getString("error.cd.pathNoExist"));
        }
    }

    @Override
    public String toString()
    {
        return "cd";
    }
}
